package com.yfw.maple_leaf_store.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yfw.maple_leaf_store.common.BaseContext;
import com.yfw.maple_leaf_store.common.R;
import com.yfw.maple_leaf_store.domain.Goods;
import com.yfw.maple_leaf_store.domain.User;
import com.yfw.maple_leaf_store.dto.EditUserDto;
import com.yfw.maple_leaf_store.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author: yfw
 * @date: 2022/6/14 19:43
 * com.yfw.maple_leaf_store.controller
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * @param map
     * @param request
     * @return 返回提示信息
     */
    @PostMapping(value = "/login")
    public R<String> login(@RequestBody Map map, HttpServletRequest request){

        log.info(map.toString());

        //获取手机号
        String phone = map.get("phone").toString();
//        String phone = ruser.getPhone();

        //获取密码
        String password = map.get("password").toString();
//        String password = ruser.getPassword();

        //获取验证码
        String code = map.get("checkcode").toString();

        log.info("code:{}",code);

        //从Session中获取保存的验证码
        String codeInSession = (String) request.getSession().getAttribute("CHECKCODE_SERVER");
        request.getSession().removeAttribute("CHECKCODE_SERVER");
        log.info("codeInSession : {}",codeInSession);

        //进行验证码的比对（页面提交的验证码和Session中保存的验证码比对）
        if(codeInSession != null && codeInSession.equalsIgnoreCase(code)){
            //如果能够比对成功，说明登录成功

            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone).eq(User::getPassword,password);

            User user = userService.getOne(queryWrapper);
            if(user == null){
                R.error("登录失败，用户名或密码错误");
            }
            request.getSession().setAttribute("user",user.getId());//保存session
            return R.success(""+user.getId());
        }
        return R.error("登录失败，验证未通过");
    }


    /**
     * 用户注册
     * @param user
     * @return 返回提示信息
     */
    @PostMapping("/register")
    public R<String> login(@RequestBody User user) {
        user.setAvatar("user.png");
        log.info(String.valueOf(user));
        userService.save(user);
        return R.success("注册成功");
    }

    /**
     * 个人中心
     * @return
     */
    @GetMapping("/aboutMe")
    public R<User> aboutMe(){
        //获取当前id
        Long currentId = BaseContext.getCurrentId();
//        Long currentId = Long.valueOf("1537801628956426242");//测试
        //根据id查询用户信息
        User user = userService.getById(currentId);
        return R.success(user);
    }

    /**
     * 编辑个人信息
     * @param userDto
     * @return
     */
    @PutMapping("/edit")
    public R<String> edit(@RequestBody EditUserDto userDto){
        //获取当前用户id
        Long currentId = BaseContext.getCurrentId();
//        Long currentId = Long.valueOf("1537254048795111425");//测试
        log.info("{}",userDto);
        User user = userDto.getUser();
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getId,currentId);
        String password  = userService.getOne(userLambdaQueryWrapper).getPassword();
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        if(userDto.getOldPwd().equals(password)){//旧密码比较新密码
            wrapper.set(user.getName() != null, User::getName, user.getName())
                    .set(user.getPhone() != null, User::getPhone,user.getPhone())
                    .set(user.getPassword() != null,User::getPassword,user.getPassword())
                    .set(user.getAvatar()!=null,User::getAvatar,user.getAvatar())
                    .set(user.getSex()!=null,User::getSex,user.getSex())
                    .eq(User::getId,currentId);
            userService.update(wrapper);
            return R.success("修改成功");
        }
        return R.error("修改密码不匹配，请检查是否输入正确");
    }
}

